# coding:utf-8
from typing import Dict, List

import pydantic
from fastapi import Query

from app.models.system import SystemMenu, SystemRoleMenu
from app.admin.schemas.system import PostBase, PostUpdate, SystemMenuOutDB
from app.utils.array import ArrayUtil


class SystemMenuService:
    # 列表
    async def tree_list(self, query: Query):
        lists = await SystemMenu.filter(query).order_by("sort").all()
        menus = [await obj.to_dict(m2m=True) for obj in lists]
        return ArrayUtil.list_to_tree(menus, 'id', 'pid', 'children')

    async def get_child_count(self, item_id: int):
        count = await SystemMenu.filter(pid=item_id).count()
        return count

    async def get_id(self, user_id: int):
        user = await SystemMenu.get_or_none(id=user_id)
        return user

    async def find(self, query: Query):
        user = await SystemMenu.get_or_none(query)
        return user

    async def create(self, obj_in: PostBase):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        user = await SystemMenu.create(**obj_dict)
        return user

    async def update(self, obj_in: PostUpdate):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()

        # 删除键
        item_id = obj_dict.pop('id')
        user = await SystemMenu.filter(id=item_id).update(**obj_dict)
        return user

    async def remove(self, item_id: int):
        item = await SystemMenu.get_or_none(id=item_id)
        print(item)
        if item:
            await item.delete()
            return True
        else:
            return False
